package tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.HashMap;
import java.util.Stack;

public final class InsertTag extends TagSupport {

    private Stack<HashMap> stack;
    private String attribute;

    public int doStartTag() {
        stack = getStack();
        stack.push(new HashMap());
        return EVAL_BODY_INCLUDE;
    }

    public int doEndTag() throws JspException {
        pageContext.setAttribute("attribute", attribute, PageContext.REQUEST_SCOPE);
        try {
            pageContext.include("Template.jsp");
        } catch (Exception ex) {
            throw new JspException(ex.getMessage());
        }
        stack.pop();
        return EVAL_PAGE;
    }

    public void release() {
        stack = null;
        attribute = null;
        super.release();
    }

    public Stack<HashMap> getStack() {
        Stack s = (Stack)pageContext.getAttribute("stack", PageContext.REQUEST_SCOPE);
        if (s==null) {
            s = new Stack<HashMap>();
            pageContext.setAttribute("stack", s, PageContext.REQUEST_SCOPE);
        }
        return s;
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
}